package com.shengde.jinwawaforleader.model.homePage;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.shengde.jinwawaforleader.R;
import com.shengde.jinwawaforleader.base.BaseActivity;
import com.shengde.jinwawaforleader.bean.User;
import com.shengde.jinwawaforleader.network.BaseProtocol;
import com.shengde.jinwawaforleader.network.protocolbean.ProSchoolNewsList;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * 学校公告
 * Created by Administrator on 2016/9/1 0001.
 */
public class EveryConsultActivity extends BaseActivity implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
	private static final String TAG = "EveryConsultActivity";
	private static final int HOTNEWS_MORE = 1;
	private static final int FIRST_IN = 2;
	private static final int NO_MORE = 3;
	private static final int ADD_SUCCEED = 4;
	private static final int FLUSH_SUCCEED = 5;
	private static final int DELETE_SUCCESS = 6;
	private static final int OK_SUCCESS = 7;
	private List<ProSchoolNewsList.NoticesBean> NoticesBean; //
	private ArrayList NoticesBeans;

	private LinearLayout loading_main;  //加载中..

	private TextView tv_back;
	private TextView tv_title;
	private TextView fill_add;
	private SchoolNewAdapter mHotNewsAdatpter;
	private ListView lv_hotnews_more; //热门咨询的listview
	private PullToRefreshListView pull_refresh_list; //下拉刷新 和上拉加载跟多

	int curpage = 1;
	int totalpages;

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
				case FIRST_IN:
					loading_main.setVisibility(View.GONE);
					mHotNewsAdatpter = new SchoolNewAdapter(EveryConsultActivity.this, NoticesBeans);
					lv_hotnews_more.setAdapter(mHotNewsAdatpter);
					break;
				case FLUSH_SUCCEED:
					pull_refresh_list.onRefreshComplete();
					judge();
					Toast.makeText(EveryConsultActivity.this, getString(R.string.refresh_success), Toast.LENGTH_SHORT).show();
					break;
				case ADD_SUCCEED:
					pull_refresh_list.onRefreshComplete();
					judge();
					Toast.makeText(EveryConsultActivity.this, getString(R.string.loading_success), Toast.LENGTH_SHORT).show();
					break;
				case NO_MORE:
					pull_refresh_list.onRefreshComplete();
					judge();
					Toast.makeText(EveryConsultActivity.this, getString(R.string.xlistview_footer_no_more_msg), Toast.LENGTH_SHORT).show();
					break;
				case DELETE_SUCCESS:
					judge();
					Toast.makeText(EveryConsultActivity.this, getString(R.string.delete_success), Toast.LENGTH_SHORT).show();
					break;

			}
		}

		;
	};

	@Override
	public void onRoot(Bundle savedInstanceState) {
		setContentView(R.layout.every_consult_activity);
	}

	@Override
	public void initView() {
		loading_main = (LinearLayout) findViewById(R.id.loading_main);
		tv_back = (TextView) findViewById(R.id.tv_back);
		tv_title = (TextView) findViewById(R.id.tv_title);
		fill_add = (TextView) findViewById(R.id.fill_add);
		pull_refresh_list = (PullToRefreshListView) findViewById(R.id.lv_hotnews_more);
		lv_hotnews_more = pull_refresh_list.getRefreshableView();
	}

	@Override
	public void initData() {
		NoticesBeans = new ArrayList<>();
		fill_add.setText(getString(R.string.Send_tie));
		tv_title.setText(getString(R.string.everyday_consult));
		pull_refresh_list.getLoadingLayoutProxy(false, true).setPullLabel(getString(R.string.xlistview_footer_hint_normal));
		pull_refresh_list.getLoadingLayoutProxy(false, true).setReleaseLabel(getString(R.string.xlistview_footer_hint_ready));
		showHotNews(curpage, FIRST_IN);

	}

	@Override
	public void initListener() {
		fill_add.setOnClickListener(this);
		tv_back.setOnClickListener(this);
		lv_hotnews_more.setOnItemClickListener(this);
		lv_hotnews_more.setOnItemLongClickListener(this);
		//刷新监听
		pull_refresh_list.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
				NoticesBeans.clear();
				curpage = 1;
				showHotNews(curpage, FLUSH_SUCCEED);
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
				curpage++;
				if (curpage > totalpages) {
					curpage--;
					mHandler.sendEmptyMessage(NO_MORE);
				} else {
					showHotNews(curpage, ADD_SUCCEED);
				}
			}
		});

	}

	//判断 刷新状态后的 调用方法
	private void judge() {
		if (mHotNewsAdatpter == null) {
			mHotNewsAdatpter = new SchoolNewAdapter(EveryConsultActivity.this, NoticesBeans);
			lv_hotnews_more.setAdapter(mHotNewsAdatpter);
		} else {
			Log.i(TAG, "judge: mHotNewsAdatpter" + mHotNewsAdatpter.getCount());
			mHotNewsAdatpter.notifyDataSetChanged();
		}
	}

	@Override
	public void onWidgetClick(View view) {
		switch (view.getId()) {
			case R.id.tv_back:
				finish();
				break;
			case R.id.fill_add:
				Intent intent = new Intent(EveryConsultActivity.this, SchoolNoteFabuActivity.class);
				startActivityForResult(intent, OK_SUCCESS);
				break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == OK_SUCCESS && resultCode == 999) {
			Log.i(TAG, "onActivityResult: result" + resultCode);
			NoticesBeans.clear();
			showHotNews(1,FLUSH_SUCCEED);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Intent intent = new Intent(EveryConsultActivity.this,
				SchoolNewsInformationItemActivity.class);
		intent.putExtra("noticeId", NoticesBean.get(position - 1)
				.getId() + "");
		intent.putExtra("noticeTitle", NoticesBean.get(position - 1)
				.getTitle());
		intent.putExtra("imgpath", NoticesBean.get(position - 1)
				.getPicturepath());
		Log.i(TAG, "onItemClick: lasttime" + NoticesBean.get(position - 1).getLasttime());
		intent.putExtra("lastTime", NoticesBean.get(position - 1)
				.getLasttime());
		startActivity(intent);
	}

	/**
	 * 学校公告列表的 网络请求
	 *
	 * @param curpage
	 * @param flag
	 */
	private void showHotNews(int curpage, final int flag) {
		//http://120.76.155.123:8080/api/director/InfosList?type=&curpage=1&teacherid=1
		String url = "";
		if (User.isTest) {
			url = BaseProtocol.HOST_BASE_TEST + "/teacher/NoticeList";
		} else {
			url = BaseProtocol.HOST_BASE + "/teacher/NoticeList";
		}
		RequestParams params  = BaseProtocol.getRequestParams(url);
		params.addHeader("", "");
		params.addParameter("type", 4);
		params.addParameter("curpage", curpage);
		params.addParameter("teacherflag", 0);
		params.addParameter("id", User.getSchoolId(this));
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				ProSchoolNewsList pro_hot_news_list = new Gson().fromJson(result, ProSchoolNewsList.class);
				if (pro_hot_news_list != null && pro_hot_news_list.getCode() == 0) {
					NoticesBean = pro_hot_news_list.getNotices();
					totalpages = pro_hot_news_list.getTotalpages();
					Log.i(TAG, "onSuccess: size" + NoticesBean.size());
					for (int i = 0; i < NoticesBean.size(); i++) {
						NoticesBeans.add(NoticesBean.get(i));
					}
					mHandler.sendEmptyMessage(flag);
				}

			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {

			}

			@Override
			public void onCancelled(CancelledException cex) {

			}

			@Override
			public void onFinished() {

			}
		});

	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
		final Dialog dialog = new Dialog(this, R.style.dialog);
		View contentView = LayoutInflater.from(this).inflate(
				R.layout.dialog_exit, null);
		dialog.setContentView(contentView);
		dialog.setCanceledOnTouchOutside(true);
		dialog.show();
		TextView textView1990 = (TextView) contentView.findViewById(R.id.textView1990);
		textView1990.setText("确定删除当前会话吗?");
		TextView ok = (TextView) contentView.findViewById(R.id.button_ok);
		TextView cacel = (TextView) contentView.findViewById(R.id.button_cacel);
		ok.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();

				showDeletePublicInfo(position);
			}
		});
		cacel.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		return true;
	}

	/**
	 * 删除 公告接口
	 *
	 * @param position
	 */
	private void showDeletePublicInfo(int position) {
		String url = "";
		if (User.isTest) {
			url = BaseProtocol.HOST_BASE_TEST + "/teacher/NoticeDelete";
			;
		} else {
			url = BaseProtocol.HOST_BASE + "/teacher/NoticeDelete";
		}
		RequestParams params  = BaseProtocol.getRequestParams(url);
		params.addParameter("userid", User.getUserLoginAccount(this));
		params.addParameter("noticeid", NoticesBean.get(position - 1).getId());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				NoticesBeans.clear();
				showHotNews(curpage,DELETE_SUCCESS);
//				mHandler.sendEmptyMessage(DELETE_SUCCESS);
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
			}

			@Override
			public void onCancelled(CancelledException cex) {
			}

			@Override
			public void onFinished() {
			}
		});
	}
}
